initWS('ws://localhost:8080/poultry/ws/admin/console')
var ws;
function initWS(wsUrl){
	addLog('开始连接串口控制程序')
	ws = new WebSocket(wsUrl);
	ws.onopen = function(evt) { 
		addLog('连接串口控制程序成功')
		setRemind('已连接串口控制程序')
		console.log("Connection open...")
	};
	ws.onmessage = function(evt) {
		console.log( "Received Message: " + evt.data)
		var data = evt.data
		if(data.indexOf('log:')==0){
			addLog(data.substring(4))
		}else if(data.indexOf('READ:')==0){
			addDataLog(data.substring(5))
		}else if(data.indexOf('WRITE:')==0){
			addDataLog(data.substring(6))
		}
	};
	ws.onclose = function(evt) {
		setWarning('串口控制程序已断开')
		addLog('串口控制程序已断开')
		console.log("Connection closed.");
	};
}


function setRemind(remind){
	console.log('setRemind:'+remind)
	$('#warning').text('')
	$('#remind').text(remind)
}

function setWarning(warning){
	console.log('setWarning:'+warning)
	$('#remind').text('')
	$('#warning').text(warning)
}

function getPort(){
	var port = $('#select-port').val()
	if((!port) || port == 'null'){
		console.log('getPort:return:null:'+port)
		return null
	}else{
		console.log('getPort:return:'+port)
		return port
	}
}

function myAlert(text){
	console.log('myAlert:'+text)
	$('#alert-modal-bd').text(text)
	$('#alert-modal').modal('open')
}

function addLog(text){
	console.log("addLog:"+text)
	//var d = new Date()
	//var dStr = d.getFullYear() +'-'+d.getMonth()+'-'+d.getUTCDate()+' '+d.getHours()+':'+d.getMinutes()+':'+d.getSeconds()+'.'+d.getMilliseconds();
	$('#log-panel-content').prepend('<p>'+text+'</p>')
}

function addDataLog(text){
	console.log("addDataLog:"+text)
	$('#dataLog-panel-content').prepend('<p>'+text+'</p>')
}

$('#select-port').on('change',function(e){
	var obj = e.currentTarget
	var port = obj.value
	if( (!port) || port=='null'){
		//setWarning('请选择正确的串口');
	}else{
		//setRemind('已选择串口：'+obj.value);
	}
})

$('#conn-btn').on('click',function(e){
	var port = getPort()
	if(!port){
		myAlert('请选择正确的串口')
		return
	}
	/*
	var btn = e.currentTarget
	var loading = '<i class="am-icon-spinner am-icon-spin"></i>连接中';
	var cssClass = btn.getAttribute('class')
	btn.setAttribute('disabled','disabled')
	btn.innerHTML = loading
	*/
	addLog('开始连接串口：'+port)
	ws.send("conn:"+port);
})

$('#findCard-btn').on('click',function(e){
	ws.send("findCard:");
})
//killConflict

$('#killConflict-btn').on('click',function(e){
	ws.send('killConflict:')
})

$('#choseCard-btn').on('click',function(e){
	ws.send('choseCard:')
})

$('#downloadPW-btn').on('click',function(e){
	ws.send('downloadPW:')
})

$('#breakoff-btn').on('click',function(e){
	addLog('取消连接串口')
	var connBtn = $('#conn-btn')
	connBtn.html('连接')
	connBtn.removeAttr('disabled')
})

$('#log-panel-clear').on('click',function(e){
	$('#log-panel-content').html('')
})


